package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件访问控制器
 * 处理静态文件的HTTP访问
 */
@Slf4j
@RestController
@RequestMapping("/images")
public class FileAccessController {

    @Value("${file.upload.path:./uploads/}")
    private String uploadPath;

    /**
     * 访问图片文件
     */
    @GetMapping("/**")
    public ResponseEntity<Resource> getImage(HttpServletRequest request) {
        try {
            // 获取请求路径
            String requestPath = request.getRequestURI();
            // 移除 /images 前缀
            String filePath = requestPath.substring("/images".length());
            
            // 确保上传路径是绝对路径
            File baseUploadDir = new File(uploadPath);
            if (!baseUploadDir.isAbsolute()) {
                baseUploadDir = new File(System.getProperty("user.dir"), uploadPath);
            }
            
            // 构建完整的文件路径
            File file = new File(baseUploadDir, "images" + filePath);
            
            log.debug("请求图片文件: {}", file.getAbsolutePath());
            
            // 检查文件是否存在
            if (!file.exists() || !file.isFile()) {
                log.warn("图片文件不存在: {}", file.getAbsolutePath());
                return ResponseEntity.notFound().build();
            }
            
            // 安全检查：确保文件在允许的目录内
            String canonicalFilePath = file.getCanonicalPath();
            String canonicalBasePath = baseUploadDir.getCanonicalPath();
            if (!canonicalFilePath.startsWith(canonicalBasePath)) {
                log.warn("尝试访问不安全的文件路径: {}", canonicalFilePath);
                return ResponseEntity.notFound().build();
            }
            
            // 创建资源
            Resource resource = new FileSystemResource(file);
            
            // 获取文件的MIME类型
            Path path = Paths.get(file.getAbsolutePath());
            String contentType = Files.probeContentType(path);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            
            log.debug("返回图片文件: {}, 类型: {}", file.getName(), contentType);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CACHE_CONTROL, "max-age=3600") // 缓存1小时
                    .body(resource);
                    
        } catch (IOException e) {
            log.error("访问图片文件时发生错误", e);
            return ResponseEntity.notFound().build();
        }
    }
} 